from abc import ABC, abstractmethod
import requests
import json
from openai import OpenAI
from logger import LOG  # 导入日志工具

class ContentAssistant(ABC):
    """
    聊天机器人基类，提供聊天功能。
    """
    def __init__(self, prompt_file="prompts/content_assistant.txt",
                 api_key=None, model="doubao-1-5-pro-32k-250115",
                 api_url="https://ark.cn-beijing.volces.com/api/v3"):
        self.prompt_file = prompt_file
        self.client = OpenAI(
            base_url=api_url,
            api_key=api_key
        )
        self.model = model
        self.prompt = self.load_prompt()
        LOG.debug(f"[Formatter Prompt]{self.prompt}")

    def load_prompt(self):
        """
        从文件加载系统提示语。
        """
        try:
            with open(self.prompt_file, "r", encoding="utf-8") as file:
                return file.read().strip()
        except FileNotFoundError:
            raise FileNotFoundError(f"找不到提示文件 {self.prompt_file}!")

    def call_doubao_api(self, input_content):
        """
        调用豆包大模型 API。

        参数:
            input_content (str): 输入内容

        返回:
            object: API 响应对象
        """
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }

        data = {
            "model": self.model,
            "prompt": f"{self.prompt}\n{input_content}",
            "max_tokens": 512,
            "temperature": 0.8,
            "top_p": 0.95
        }

        try:
            response = requests.post(self.api_url, headers=headers, data=json.dumps(data))
            response.raise_for_status()
            return response
        except requests.exceptions.RequestException as e:
            LOG.error(f"API 请求错误: {e}")
            raise
        except json.JSONDecodeError as e:
            LOG.error(f"JSON 解码错误: {e}")
            raise
        except Exception as e:
            LOG.error(f"发生错误: {e}")
            raise

    def create_assistant(self):
        """
        初始化聊天机器人，包括系统提示和消息历史记录。
        """
        # 移除递归创建实例的代码
        pass

    def adjust_single_picture(self, markdown_content):

        """
        调整单图内容
        参数:
            markdown_content (str): PowerPoint markdown 原始格式

        返回:
            str: 格式化后的 markdown 内容
        """
        try:
            completion = self.client.chat.completions.create(
                model=self.model,
                messages=[
                    {"role": "user", "content": markdown_content}
                ],
                temperature=0.8,
                max_tokens=512,
                top_p=0.95
            )

            adjusted_content = completion.choices[0].message.content
            LOG.debug(f"[Assistant 内容重构后]\n{adjusted_content}")
            return adjusted_content

        except Exception as e:
            LOG.error(f"API请求异常: {str(e)}")
            raise
